package br.edu.ufcg.dsc.services;

import java.util.List;

import javax.persistence.EntityTransaction;

import br.edu.ufcg.dsc.domain.Loan;

public class LoanService extends BaseService {

	@SuppressWarnings("unchecked")
	public static List<Loan> findByUser(String login) {
		return (List<Loan>) entity
				.createQuery(
						"SELECT l FROM br.edu.ufcg.dsc.domain.Loan l WHERE l.open = TRUE AND l.user.login = :login")
				.setParameter("login", login).getResultList();
	}

	public static Loan findByUnit(String unit) {
		return (Loan) entity
				.createQuery(
						"SELECT l FROM br.edu.ufcg.dsc.domain.Loan l WHERE l.open = TRUE AND l.unit.id = :unit")
				.setParameter("unit", unit).getSingleResult();
	}

	public static void persist(Loan l) {
		EntityTransaction tx = entity.getTransaction();

		tx.begin();

		try {
			entity.persist(l);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}
	}

}
